import time

from datetime import date, datetime, timedelta
from flask import render_template, request, jsonify, current_app, session, g, abort

from info import user_login_data, constants, db
from info.models import User, News, Category
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import admin_blu


@admin_blu.route("/news_type", methods=["GET", "POST"])
def news_type():
    if request.method == "GET":
        categories = Category.query.all()
        categories_dict_li = []
        for category in categories:
            categories_dict_li.append(category.to_dict())

        categories_dict_li.pop(0)
        data = {
            "categories": categories_dict_li
        }

        return render_template("admin/news_type.html", data=data)

    cid = request.json.get("id", None)
    cname = request.json.get("name", None)

    if not cname:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 修改
    if cid:
        try:
            cid = int(cid)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        try:
            category = Category.query.get(cid)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="未查询到分类数据")

        category.name = cname

    else:
        category = Category()
        category.name = cname
        db.session.add(category)

    return jsonify(errno=RET.OK, errmsg="OK")


@admin_blu.route("/news_edit_detail", methods=["GET", "POST"])
def news_edit_detail():
    if request.method == "GET":
        news_id = request.args.get("news_id", None)
        if not news_id:
            abort(404)
        try:
            news_id = int(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template("admin/news_edit_detail.html", errmsg="参数错误")

        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template("admin/news_edit_detail.html", errmsg="查询数据错误")

        if not news:
            return render_template("admin/news_edit_detail.html", errmsg="未查询到数据")

        categories = None
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return render_template("admin/news_edit_detail.html", errmsg="查询数据错误")

        categories_dict_li = []
        for category in categories:
            cate_dict = category.to_dict()
            if category.id == news.category_id:
                cate_dict["is_selected"] = True
            categories_dict_li.append(cate_dict)

        categories_dict_li.pop(0)

        data = {
            "news": news.to_dict(),
            "categories": categories_dict_li
        }
        return render_template("admin/news_edit_detail.html", data= data)

    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    if not all([news_id, title, digest, content, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        new_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="数据查询失败")

    if not news:
        return jsonify(errno=RET.PARAMERR, errmsg="未查询到数据")

    # 1.2 尝试读取图片
    if index_image:
        try:
            index_image = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        # 2. 将标题图片上传到七牛
        try:
            key = storage(index_image)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key

    # 3. 设置相关数据
    news.title = title
    news.digest = digest
    news.content = content
    news.category_id = category_id

    # 4. 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
    # 5. 返回结果
    return jsonify(errno=RET.OK, errmsg="编辑成功")


@admin_blu.route("/news_edit")
def news_edit():
    page = request.args.get("p", 1)
    # args
    keywords = request.args.get("keywords", None)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    filters = [News.status == 0]
    if keywords:
        filters.append(News.title.contains(keywords))

    news = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(*filters).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    data = {
        "news_list": news,
        "current_page": current_page,
        "total_page": total_page
    }

    return render_template("admin/news_edit.html", data=data)


@admin_blu.route("/news_review_action", methods=["POST"])
def news_review_action():
    news_id = request.json.get("news_id", None)
    action = request.json.get("action", None)

    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if not action in("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBDATA, errmsg="查询数据失败")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到新闻")

    if action ==  "accept":
        news.status = 0
    else:
        reason = request.json.get("reason", None)
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="请输入拒绝原因")
        news.status = -1
        news.reason = reason

    return jsonify(errno=RET.OK, errmsg="OK")


@admin_blu.route("/news_review_detail/<int:news_id>")
def news_review_detail(news_id):
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        render_template("admin/news_review_detail.html", errmsg="未查询到此新闻")

    data = {"news": news.to_dict()}

    return render_template("admin/news_review_detail.html", data=data)



@admin_blu.route("/news_review")
def news_review():
    page = request.args.get("p", 1)
    # args
    keywords = request.args.get("keywords", None)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    filters = [News.status!=0]
    if keywords:
        filters.append(News.title.contains(keywords))

    news = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(*filters).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    data = {
        "news_list": news,
        "current_page": current_page,
        "total_page": total_page
    }

    return render_template("admin/news_review.html", data=data)


@admin_blu.route("/user_list")
def user_list():
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    current_page = 1
    total_page = 1
    user = []
    try:
        paginate = User.query.filter(User.is_admin==0).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        current_page = paginate.page
        total_page = paginate.pages
        user = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    data = {
        "current_page": current_page,
        "total_page": total_page,
        "users": user
    }

    return render_template("admin/user_list.html", data=data)


@admin_blu.route("/user_count")
def user_count():
    total_count = 0
    day_count = 0
    mon_count = 0
    try:
        total_count = User.query.filter(User.is_admin==0).count()
    except Exception as e:
        current_app.logger.error(e)

    # 获取当前时间
    t = time.localtime()
    mon_begin_date_str = "%d-%2d-01" %(t.tm_year, t.tm_mon)
    mon_begin_date = datetime.strptime(mon_begin_date_str, "%Y-%m-%d")
    try:
        mon_count = User.query.filter(User.is_admin==0, User.create_time>mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 日查新数
    day_begin_date_str = "%d-%2d-%2d" % (t.tm_year, t.tm_mon, t.tm_mday)
    day_begin_date = datetime.strptime(day_begin_date_str, "%Y-%m-%d")
    try:
        day_count = User.query.filter(User.is_admin == 0, User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询图表信息
    active_date = []
    active_count = []
    for i in range(31):
        begin_date = day_begin_date - timedelta(days=i)
        end_date = begin_date + timedelta(days=1)
        # print(begin_date, end_date)
        try:
            count = User.query.filter(User.is_admin == 0, User.last_login > begin_date, User.last_login < end_date).count()
        except Exception as e:
            current_app.logger.error(e)
        active_date.append(begin_date.strftime("%Y-%m-%d"))
        active_count.append(count)

    active_date.reverse()
    active_count.reverse()

    data = {
        "total_count": total_count,
        "day_count": day_count,
        "mon_count": mon_count,
        "active_date": active_date,
        "active_count": active_count
    }
    return render_template("admin/user_count.html", data=data)


@admin_blu.route("/index")
@user_login_data
def index():
    user = g.user
    return render_template("admin/index.html", user=user.to_dict())


@admin_blu.route("/login", methods=["GET", "POST"])
@user_login_data
def login():
    if request.method == "GET":
        user = g.user
        user_id = session.get("user_id", None)
        is_admin = session.get("is_admin", None)
        if user_id and is_admin:
            return render_template("admin/index.html", user=user.to_dict())

        return render_template("admin/login.html")

    # 获取参数
    username = request.form.get("username", None)
    password = request.form.get("password", None)
    # 校验参数
    if not all([username, password]):
        return render_template("admin/login.html", errmsg="参数错误")

    try:
        user = User.query.filter(User.nick_name==username).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="用户信息查询失败")

    if not user:
        return render_template("admin/login.html", errmsg="未查到用户信息")

    if not user.check_passowrd(password):
        return render_template("admin/login.html", errmsg="用户名或密码错误")

    # 保存用户登录信息
    session["user_id"] = user.id
    session["mobile"] = user.mobile
    session["nick_name"] = user.nick_name
    session["is_admin"] = user.is_admin

    # 跳转到后台管理页面
    return render_template("admin/index.html", user=user.to_dict())

